import { app, BrowserWindow, ipcMain,shell  } from 'electron';
import * as path from 'path';
import * as fs from 'fs';

let mainWindow: BrowserWindow | null = null;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 700,
    webPreferences: {
      contextIsolation: true,               // 推荐开启，安全
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
    }
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    // 开发模式：加载 vite dev server
    mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
    mainWindow.webContents.openDevTools();
  } else {
    // 生产模式：加载打包好的文件
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

// 监听渲染进程发来的读取文件夹请求
ipcMain.handle('read-directory', async (event, dirPath: string) => {
  try {
    const dirents = await fs.promises.readdir(dirPath, { withFileTypes: true });

    const entries = await Promise.all(
      dirents.map(async dirent => {
        const fullPath = path.join(dirPath, dirent.name);
        const stats = await fs.promises.stat(fullPath);
        const parentPath = path.dirname(fullPath);

        return {
          name: dirent.name,
          path: fullPath,
          parentPath: parentPath,
          isFile: dirent.isFile(),
          isDirectory: dirent.isDirectory(),
          size: stats.size,
          createdAt: stats.birthtime,
          updatedAt: stats.mtime
        };
      })
    );

    return { success: true, data: entries };
  } catch (error: any) {
    return { success: false, message: error.message };
  }
});

// 创建文件夹
ipcMain.handle('create-folder', async (_, parentPath: string, folderName: string) => {
  const fullPath = path.join(parentPath, folderName);
  try {
    if (!fs.existsSync(fullPath)) {
      fs.mkdirSync(fullPath);
      return { success: true, data: fullPath };
    } else {
      return { success: false, error: '文件夹已存在' };
    }
  } catch (error:any) {
    return { success: false, error: error.message };
  }
});

// 重命名文件夹
ipcMain.handle('rename-folder', async (_, oldPath: string, newName: string) => {
  try {
    const newPath = path.join(path.dirname(oldPath), newName);
    fs.renameSync(oldPath, newPath);
    return { success: true, data: newPath };
  } catch (error:any) {
    return { success: false, error: error.message };
  }
});
ipcMain.handle('delete-folder', async (_, folderPath: string) => {
  try {
    // 递归删除文件夹（包含子文件和文件夹）
    await fs.promises.rm(folderPath, { recursive: true, force: true });
    return { success: true };
  } catch (error: any) {
    return { success: false, error: error.message };
  }
});

ipcMain.handle('search-in-directory', async (_, rootPath: string, keyword: string) => {
  const results: {
    name: string;
    path: string;
    parentPath: string;
    isFile: boolean;
    isDirectory: boolean;
  }[] = [];
  async function searchDir(currentPath: string) {
    try {
      const dirents = await fs.promises.readdir(currentPath, { withFileTypes: true });

      for (const dirent of dirents) {
        const fullPath = path.join(currentPath, dirent.name);
        const matches = dirent.name.includes(keyword);
        const isDir = dirent.isDirectory();

        if (matches) {
          results.push({
            name: dirent.name,
            path: fullPath,
            parentPath: currentPath,
            isFile: dirent.isFile(),
            isDirectory: isDir,
          });
        }

        if (isDir) {
          await searchDir(fullPath); // 递归搜索子目录
        }
      }
    } catch (err) {
      console.error(`搜索目录时出错: ${currentPath}`, err);
    }
  }

  await searchDir(rootPath);

  return { success: true, data: results };
});


ipcMain.handle('open-file-external', async (_, filePath: string) => {
  try {
    await shell.openPath(filePath); // 自动使用系统默认程序打开文件
    return { success: true };
  } catch (err: any) {
    return { success: false, error: err.message };
  }
});

ipcMain.handle('get-folder-steps', async (_, rootPath: string, targetPath: string) => {
  try {
    const relative = path.relative(rootPath, targetPath);
    if (relative.startsWith('..')) throw new Error('targetPath is not inside rootPath');

    const segments = relative.split(path.sep).filter(Boolean);
    const result: string[] = [];

    let current = rootPath;
    for (const segment of segments) {
      current = path.join(current, segment);
      result.push(current);
    }

    return { success: true, data: result };
  } catch (err: any) {
    return { success: false, error: err.message };
  }
});
const writeStreams: Map<string, fs.WriteStream> = new Map()
ipcMain.on('upload-chunk', (event, { name, path: dir, chunk, isFirst, isLast }) => {
  const fullPath = path.join(dir, name)
  if (isFirst) {
    // 如果已存在，重命名
    let finalPath = fullPath
    let index = 1
    const { name: baseName, ext } = path.parse(name)

    while (fs.existsSync(finalPath)) {
      finalPath = path.join(dir, `${baseName}(${index++})${ext}`)
    }

    const stream = fs.createWriteStream(finalPath, { flags: 'w' })
    writeStreams.set(name, stream)
    stream.write(Buffer.from(chunk))
  } else {
    const stream = writeStreams.get(name)
    if (stream) {
      stream.write(Buffer.from(chunk))
    }
  }

  if (isLast) {
    const stream = writeStreams.get(name)
    if (stream) {
      stream.end()
      writeStreams.delete(name)
    }
  }
})

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});


// 关闭所有窗口时退出（macOS 除外）
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});
